package com.blog.controller;

import com.blog.check.result.Result;
import com.blog.form.ProfileForm;
import com.blog.service.service.ProfileService;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * 配置控制器
 *
 * @author 泡面ing
 * @date 2021/11/17
 */
@Controller
@RequestMapping("/profile")
public class ProfileController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    ProfileService profileService;

    @Autowired
    public void setProfileService(ProfileService profileService) {
        this.profileService = profileService;
    }

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public Result get(HttpServletResponse response) {
        Result result;
        try {
            result = profileService.get();

        } catch (Exception e) {
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            result = Result.failure("系统异常：" + e.getMessage());
            logger.error("查询信息异常：", e);
        }
        return result;
    }



    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public Result save(@RequestBody ProfileForm profileForm, HttpServletResponse response) {
        Result result;
        try {
            result = profileService.save(profileForm);
            if (result.getCode() != Result.SUCCESS) {
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                return result;
            }
            response.setStatus(HttpStatus.SC_CREATED);
        } catch (Exception e) {
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            result = Result.failure("系统异常：" + e.getMessage());
            logger.error("查询信息异常：", e);
        }
        return result;
    }

    @RequestMapping(method = RequestMethod.PUT)
    @ResponseBody
    public Result update(@RequestBody ProfileForm profileForm,
                         HttpServletResponse response){
        Result result;
        try{

            result = profileService.update(profileForm);
            if (result.getCode() != Result.SUCCESS){
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                return result;
            }
            response.setStatus(HttpStatus.SC_OK);
        }catch(Exception e){
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            result = Result.failure("系统异常" + e.getMessage());
            logger.error("编辑信息异常",e);
        }
        return result;
    }


}
